/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.config.CounterSignPassTypeEnum;
import com.je.bpm.core.model.task.KaiteCounterSignUserTask;
import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.ActivitiObjectNotFoundException;
import com.je.bpm.engine.history.HistoricTaskInstance;
import com.je.bpm.engine.history.HistoricVariableInstance;
import com.je.bpm.engine.impl.HistoricVariableInstanceQueryImpl;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.HistoricTaskInstanceEntity;

import java.io.Serializable;
import java.util.ListIterator;

/**
 * 获取会签标题
 */
public class GetCountersignedTitleCmd implements Command<String>, Serializable {

    private static final long serialVersionUID = 1L;
    protected String taskId;

    public GetCountersignedTitleCmd(String taskId) {
        if (taskId == null) {
            throw new ActivitiIllegalArgumentException("taskId or processInstanceId is required");
        }
        this.taskId = taskId;
    }

    @Override
    public String execute(CommandContext commandContext) {
        if (taskId != null) {
            return getTitleForTask(commandContext);
        }
        return "";
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected String getTitleForTask(CommandContext commandContext) {
        HistoricTaskInstanceEntity task = commandContext.getHistoricTaskInstanceEntityManager().findById(taskId);

        if (task == null) {
            throw new ActivitiObjectNotFoundException("No historic task exists with the given id: " + taskId, HistoricTaskInstance.class);
        }
        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(task.getProcessDefinitionId());
        FlowElement flowElement = bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());
        if (!(flowElement instanceof KaiteCounterSignUserTask)) {
            return "";
        }
        KaiteCounterSignUserTask kaiteCounterSignUserTask = (KaiteCounterSignUserTask) flowElement;
        String title = "";
        String typeName = kaiteCounterSignUserTask.getCounterSignConfig().getCounterSignPassType().getName();
        String sequentialName = "并行审批";
        if (kaiteCounterSignUserTask.getLoopCharacteristics().isSequential()) {
            sequentialName = "顺序审批";
        }
        if (kaiteCounterSignUserTask.getCounterSignConfig().getCounterSignPassType() == CounterSignPassTypeEnum.PASS_PRINCIPAL) {
            title = String.format("会签采用【%s-%s】，负责人为：%s，当前处理状态为：【%s】", typeName, sequentialName,
                    kaiteCounterSignUserTask.getCounterSignConfig().getOneBallotUserName());
        } else {
            title = String.format("会签采用【%s-%s】，比例标准为：%s，当前通过比例为：【%s】", typeName, sequentialName,
                    kaiteCounterSignUserTask.getCounterSignConfig().getAmount() + "%");
        }
        return title;
    }

    protected Object getLoopVariable(String executionId, String piid, String name) {
        HistoricVariableInstanceQueryImpl historicVariableInstanceQuery = new HistoricVariableInstanceQueryImpl();
        ListIterator<HistoricVariableInstance> list = historicVariableInstanceQuery.executionId(executionId).processInstanceId(piid).variableName(name).
                listPage(0, 100).listIterator();
        for (ListIterator<HistoricVariableInstance> it = list; it.hasNext(); ) {
            HistoricVariableInstance historicVariableInstance = it.next();
            return historicVariableInstance.getValue();
        }
        return null;
    }


}
